//
//  GSYNetworkManager.swift
//  GSY-微博-swift
//
//  Created by Song on 2017/12/6.
//  Copyright © 2017年 Song. All rights reserved.
//

import UIKit
import AFNetworking // 导入框架的文件夹的名字

// 枚举
enum GSYHTTPMethod {
    case GET
    case POST
}

/// 网络管理工具
class GSYNetworkManager: AFHTTPSessionManager {
    
    // 单例  全局访问点
    // 单例
    static let shared = GSYNetworkManager();

    
    // 使用一个函数封装 AFN 的 GET / POST 请求
    /// 封装 AFN 的 GET/POST
    ///
    /// - Parameters:
    ///   - method: GET / POST
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调[json(字典/ 数组)，是否成功]
    func request(method:GSYHTTPMethod = .GET, URLString: String, parameters:[String:Any], completion:@escaping ( _ json:Any?, _ isSuccess: Bool)->()) {
        
        // 成功回调
        let success = { (task:URLSessionDataTask, json: Any?) ->() in
            
            completion(json, true)
        }
        
        // 失败回调
        let failure = { (task:URLSessionDataTask?, error: Any)->() in
            
            print("网络请求错误 \(error)");
            
            completion(nil, false)
        }
        
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
